from odoo import api, fields, models, _
import logging

_logger = logging.getLogger(__name__)


class ReworkBom(models.Model):
    _name = 's.rework.bom'
    _rec_name = 'name'

    @api.onchange('product_id')
    def onchange_name(self):
        if self.product_id:
            self.name = self.product_id.display_name
        else:
            self.name = ''

    name = fields.Char()
    product_id = fields.Many2one('product.product', string='Product')
    bom_id = fields.Many2one('mrp.bom', string='Bom')
    line_ids = fields.One2many('s.remork.bom.line', 'rework_bom_id', string='工序')
    parent_id = fields.Many2one('s.rework.bom')
    child_ids = fields.One2many('s.rework.bom', 'parent_id', string='组件')
    is_general_template = fields.Boolean(default=False, string='通用模板')

    def write(self, vals):
        # 扫码或者删除产品订单行时重置序号
        old_lines = len(self.line_ids)
        res = super().write(vals)
        new_lines = len(self.line_ids)
        reset_sequence = self.line_ids.filtered(lambda x: not x.step)
        if reset_sequence or old_lines != new_lines:
            for index, line in enumerate(self.line_ids):
                line.step = index + 1
                line.name = line._get_workcenter_id()
        return res


class ReworkBomLine(models.Model):
    _name = 's.remork.bom.line'
    _rec_name = 'name'

    name = fields.Char(string='Name')
    workcenter_id = fields.Many2one('mrp.workcenter', string='Work center')
    step = fields.Integer(string='Step')
    work_station_id = fields.Many2one('work.station', string='Station')
    rework_bom_id = fields.Many2one('s.rework.bom')

    def _get_workcenter_id(self):
        s = '%02d' % self.step
        name = s + '.' + self.workcenter_id.display_name.strip()
        return name

    @api.onchange('workcenter_id')
    def _onchange_workcenter_id(self):
        if self.step == 0:
            bom = self.rework_bom_id
            if bom:
                bom_olines = len(bom.line_ids.ids)
                self.step = bom_olines + 1
        s = '%02d' % self.step
        if self.workcenter_id:
            self.name = s + '.' + self.workcenter_id.display_name.strip()
        self.work_station_id = self.workcenter_id.work_station_id.id

    @api.model_create_multi
    def create(self, vals_list):
        records = super(ReworkBomLine, self).create(vals_list)
        try:
            rework_bom_id = self.env['s.rework.bom'].search([('id', '=', records[0].rework_bom_id.id)])
            if len(rework_bom_id.line_ids) == len(records):
                step = 1
                for rec in records:
                    rec.step = step
                    rec.name = rec._get_workcenter_id()
                    step += 1
            else:
                max_step = \
                    sorted(rework_bom_id.order_line.filtered(lambda x: x.id not in records.ids).mapped('step'))[-1]
                for rec in records:
                    max_step += 1
                    rec.step = max_step
                    rec.name = rec._get_workcenter_id()
        except Exception as e:
            _logger.info('自动排序错误：{}'.format(e))
        return records
